package com.wjq.pay.task;


import com.alipay.api.AlipayApiException;
import com.wjq.pay.config.AlipayService;
import com.wjq.pay.entity.Order;
import com.wjq.pay.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class TaskOffOrder {


    @Autowired
    private IOrderService iOrderService;


    @Autowired
    AlipayService alipayService;

    /**
     *
     *   查询所有未支付的订单  根据订单号查询
     *
     *
     */
//@Scheduled(cron = "0/2 * * * * ?")
    public void outOrderQuery()  {

        List<Order> list = iOrderService.selectUnpayOrder();

        for(Order order :list){
            System.err.println(order.getOrderid());
            //定單号不为空
            if(order.getOrderid()!=null && !order.getOrderid().equals("")){

                String status = "";

                try {
                    status = alipayService.queryOrderStatus(order.getOrderid());
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                    log.info("订单查询异常：{}",order.getOrderid());
                }

                if(status!=null && !status.equals("")){

                    log.info("订单号：{}",order.getOrderid(),"订单状态：{}",status);

                    if(status.equals("TRADE_SUCCESS")){
                        log.info("开始补单");
                        this.updateOrderStatus(order.getOrderid());
                    }
                }
            }
        }
    }



    public void updateOrderStatus(String orderid)  {


        iOrderService.updateOrderStatus(orderid);
    }

}
